<script setup>
import { xSessionId } from '@/utils/utils'
import { defineEmits } from 'vue'

const emit = defineEmits(['success'])

const action = __SITE_CONFIG__.apiUrl + '/user/profile/avatar'
const headers = {
  Authorization: 'Bearer ' + localStorage.getItem('token'),
  'X-Session-Id': xSessionId.get(),
}

const accept = 'image/png, image/jpeg, image/jpg'

const beforeAvatarUpload = (rawFile) => {
  if (!rawFile.type.includes('image')) {
    ElMessage.error('很抱歉您上传的不是图片格式')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('您上传的图片大小超过了2MB')
    return false
  }
  return true
}

const onSuccess = (res, file) => {
  console.log(res, file)
  if (res.errcode !== 0) {
    ElMessage.error(res.errmsg)
  } else {
    ElMessage.success('头像上传成功')
    emit('success', res.data)
  }
}
</script>

<template>
  <el-upload
    :headers="headers"
    :accept="accept"
    :action="action"
    :show-file-list="false"
    :auto-upload="true"
    :before-upload="beforeAvatarUpload"
    :on-success="onSuccess"
  >
    <template #trigger>
      <slot></slot>
    </template>
  </el-upload>
</template>
